package com.ebt.m.commons.model.http;



import com.ebt.m.commons.BaseApplication;
import com.ebt.m.commons.utils.NetUtils;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * okhttp缓存
 */
public class CacheInterceptor implements Interceptor {
    @Override
    public Response intercept(Chain chain) throws IOException {
        Request request = chain.request();
        /*if (!NetUtils.isNetworkConnected(AppContext.getInstance())) {
            request = request.newBuilder()
                    .cacheControl(CacheControl.FORCE_CACHE)
                    .build();
        }*/
        Response response = chain.proceed(request);
        if (NetUtils.isNetworkConnected(BaseApplication.getBaseApplication())) {
            int maxAge = 0;
            // 有网络则不缓存
            response.newBuilder()
                    .header("Cache-Control", "public, max-age=" + maxAge)
                    .removeHeader("Pragma")
                    .build();
        } else {
            // 无网络时超时为一个月
            int maxStale = 60 * 60 * 24 * 30;
            response.newBuilder()
                    .header("Cache-Control", "public, only-if-cached, max-stale=" + maxStale)
                    .removeHeader("Pragma")
                    .build();
        }
        return response;
    }
}
